/**
 * Copyright (C) 2010 - 2013 Harry Glasgow
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.jaden.common.other;

import java.io.File;
import java.util.Map;
import java.util.TreeMap;

/**
 * Class to keep track of projects and when they were last opened
 * (Long key --> -Date.getTime() (Most recent first)).
 */
public class ReopenMap {

    private final Map<Long, File> map = new TreeMap<Long, File>();
    private int maxSize = 4;

    public void setFile(Long time, File file) {
        for (File file1 : map.values()) {
            if (file1.equals(file)) {
                // Got it, so out of here.
                return;
            }
        }
        map.put(-time, file);
        while (map.size() > maxSize) {
            map.remove(map.keySet().iterator().next());
        }
    }

    public int getSize() {
        return map.size();
    }

    public File getFile(int index) {
        if (index < 0 || index > 8) {
            throw new IllegalStateException("Bad index " + maxSize);
        } else if (index > map.size()) {
            throw new IllegalStateException("Bad index " + maxSize + ' ' +
                    map.size());
        }
        int i = 0;
        for (File file : map.values()) {
            if (i++ == index) {
                return file;
            }
        }
        throw new IllegalStateException("Could not find index " + i +
                " in map size " + map.size());
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        if (maxSize < 0 || maxSize > 9) {
            throw new IllegalStateException("Bad maxSize " + maxSize);
        }
        this.maxSize = maxSize;
        while (map.size() > maxSize) {
            map.remove(map.keySet().iterator().next());
        }
    }

    public void clear() {
        map.clear();
    }
}
